package com.mrx.xcitools.service;

import com.mrx.xcitools.constant.FileConstant;
import com.mrx.xcitools.model.JarFileInfo;
import org.codehaus.plexus.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author Mr.X
 * @since 2024-03-11 14:44
 **/
@Service
public class JarFileManageService {

    @Resource
    private ProcessManageService processManageService;

    private static final Map<String, String> jarFileMap = new ConcurrentHashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(JarFileManageService.class);

    @PostConstruct
    public void init() {
        File[] files = FileConstant.JARS_DIR.listFiles(file -> file.isFile() && file.getName().endsWith(".jar"));
        if (files == null) {
            logger.info("暂无已上传的 jar 包");
            return;
        }
        logger.info("初始化已上传的 jar: {}", (Object) files);
        for (File file : files) {
            jarFileMap.put(file.getName(), file.getAbsolutePath());
        }
    }

    public void addJarFile(File jarFile) {
        jarFileMap.put(jarFile.getName(), jarFile.getAbsolutePath());
    }

    public File getJarFile(String fileName) {
        String path = jarFileMap.get(fileName);
        Assert.hasText(path, fileName + " 文件不存在");
        return new File(path);
    }

    public List<JarFileInfo> listAll() {
        return jarFileMap.values().stream().map(File::new).map(it -> {
            Long processId = processManageService.getProcessId(it.getName());
            String size = FileUtils.byteCountToDisplaySize((int) it.length());
            return JarFileInfo.of(processId, it.getName(), it, size);
        }).collect(Collectors.toList());
    }

    public boolean delJar(String jarName) {
        logger.info("删除 jar 文件: {}", jarName);
        File jarFile = getJarFile(jarName);
        boolean deleted = jarFile.delete();
        if (deleted) {
            jarFileMap.remove(jarName);
        }
        return deleted;
    }
}
